
import { useState, useEffect } from 'react';

type WorkerCallback = (event: MessageEvent) => void;

export const useWorker = (workerFile: string, input: any): [any, boolean] => {
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    const worker = new Worker(new URL(workerFile, import.meta.url));

    const handleMessage: WorkerCallback = (event) => {
      setResult(event.data);
      setLoading(false);
    };

    worker.postMessage(input);
    worker.addEventListener('message', handleMessage);

    return () => {
      worker.removeEventListener('message', handleMessage);
      worker.terminate();
    };
  }, [input, workerFile]);

  return [result, loading];
};
